<?php

/*
  index script (controller node)
    
  Author:     Alfredo Mungo
  License:    LGPL
  Copyright:  2012
*/

define("PHI_CONTEXT_CONTROLLER", true);
require_once "core/init.php";
require_once "controllers/DefaultController.php";

// Parse the app parameters and launch it
$ctl = parse_ctl_url($_SERVER['PHP_SELF']);

if($ctl === null) { // An error occourred
  Error::raise(500, 'Miswritten PHI controller path.');
} else { // Valid controller data retrieved
  $ctl_cls = null;
    
  if(count($ctl) > 0) { // Did the client call index.php with no controller request?
    if(PHI_PHP_SCANDIR_CONSTANTS)
      $ctls = scandir(PHI_ROOTDIR . '/controllers/', SCANDIR_SORT_NONE);
    else
      $ctls = scandir(PHI_ROOTDIR . '/controllers/');
            
    $found = false;
        
    foreach($ctls as $ctlf) // Find the controller class file
      if($ctlf == $ctl[0] . '.php') {
        include PHI_ROOTDIR . '/controllers/' . $ctl[0] . '.php';
        $ctl_cls = new $ctl[0](array_slice($ctl, 1));
        $found = true;
        $ctl = array_slice($ctl, 1); // remove the class from the parameters
        break;
      }
        
    if(!$found) // If the controller class file is not found, the first parameter is probably a method or parameter of the default controller class.
      $ctl_cls = new DefaultController($ctl);
  } else
    $ctl_cls = new DefaultController(array_slice($ctl, 1));
    
  // Launch controller
  $ctl_method = null;
    
  if(count($ctl) > 0)
    $ctl_method = $ctl[0];
        
  unset($ctl);
    
  HookManager::run(HookManager::HOOK_CTL_BEFORE);
    
  if(!method_exists($ctl_cls, $ctl_method))
    if(method_exists($ctl_cls, 'hDefault'))
      $ctl_cls->hDefault(); // Call default handler
    else
      Error::raise(500);
  else {
    $ref_method = new ReflectionMethod($ctl_cls, $ctl_method);
        
    if($ref_method->isPublic()
       && !$ref_method->isConstructor()
       && !$ref_method->isDestructor()
       && !$ref_method->isStatic()
       && !$ref_method->isAbstract()) //TODO: Try implementing a $ref_method->getModifiers() solution
      $ctl_cls->{$ctl_method}();
    else
      if(method_exists($ctl_cls, 'hDefault'))
	$ctl_cls->hDefault(); // Call default handler
      else
	Error::raise(500);
  }
        
  HookManager::run(HookManager::HOOK_CTL_AFTER);
  ///
}
///
?>
